﻿using System.Diagnostics.CodeAnalysis;
using Admin.CommonLib.Models.Role;
using Admin.RazorLib.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Radzen;

namespace Admin.RazorLib.Pages;

public partial class RoleEdit
{
    private RoleEditRequestDto _editRequestDto = new();

    [Parameter] public Guid? Key { get; set; }

    [Inject] public IRoleService RoleService { get; set; }

    [Inject]
    [NotNull]
    public DialogService? DialogService { get; set; }

    async Task OnSubmit()
    {
        if (Key != null)
        {
            var result = await RoleService.UpdateRole(Key.Value, _editRequestDto);

            if (result.Succeeded)
            {
                DialogService.Close(null);
            }
        }
        else
        {
            var result = await RoleService.CreateRole(_editRequestDto);

            if (result.Succeeded)
            {
                DialogService.Close(null);
            }
        }
    }

    protected override async Task OnParametersSetAsync()
    {
        _editRequestDto = new RoleEditRequestDto();
        if (Key != null)
        {
            var result = await RoleService.GetRole(Key.Value);
            if (result.Succeeded && result.Data != null)
            {
                _editRequestDto.RoleCode = result.Data.RoleCode;
                _editRequestDto.RoleName = result.Data.RoleName;
                _editRequestDto.Description = result.Data.Description;
            }
        }
    }

    protected void CancelButtonClick(MouseEventArgs args)
    {
        DialogService.Close(null);
    }

}